package org.giovanolli.mumi.config;

import java.util.Properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 * The Class MailConfig.
 */
@Configuration
public class MailConfig {

	/** The host. */
	@Value("${mail.host}")
	private String host;

	/** The user. */
	@Value("${mail.user}")
	private String user;

	/** The pwd. */
	@Value("${mail.pwd}")
	private String pwd;

	/** The port. */
	@Value("${mail.port}")
	private int port;

	/** The protocol. */
	@Value("${mail.protocol}")
	private String protocol;

	/** The is authenticated. */
	@Value("${mail.authenticated}")
	private String isAuthenticated;

	/** The is starttls enable. */
	@Value("${mail.starttlsenable}")
	private String isStarttlsEnable;

	/**
	 * Mail sender.
	 * 
	 * @return the java mail sender
	 */
	@Bean
	public JavaMailSender mailSender() {

		JavaMailSenderImpl javaMailSenderImpl = new JavaMailSenderImpl();

		javaMailSenderImpl.setProtocol(this.protocol);
		javaMailSenderImpl.setHost(this.host);
		javaMailSenderImpl.setPort(this.port);

		if (Boolean.valueOf(isAuthenticated)) {
			javaMailSenderImpl.setUsername(this.user);
			javaMailSenderImpl.setPassword(this.pwd);
			Properties props = new Properties();
			props.setProperty("mail.smtp.auth", isAuthenticated);
			props.setProperty("mail.smtp.starttls.enable", isStarttlsEnable);
			javaMailSenderImpl.setJavaMailProperties(props);
		}

		return javaMailSenderImpl;
	}
}
